using System;
using System.Collections.Generic;
using System.Text;

namespace NBusiness.Query.SqlServer
{
    public class SqlOrderBy : IOrder
    {
        #region Member properties and fields
        private List<IColumn> _columns = new List<IColumn>();
        private SortOrder _order; 
        #endregion

        #region Constructors
        public SqlOrderBy(params IColumn[] columns)
            : this(SortOrder.Asc, columns)
        { }
        public SqlOrderBy(SortOrder order, params IColumn[] columns)
        {
            _order = order;
            _columns.AddRange(columns);
        } 
        #endregion

        #region IOrder Members

        public IList<IColumn> Columns
        {
            get { return _columns; }
        }

        public SortOrder Order
        {
            get { return _order; }
            set { _order = value; }
        }

        #endregion

        #region IRelationalElement Members

        public string ToSql()
        {
            return ToSql(new SqlQueryContext());
        }
        public string ToSql(IQueryContext context)
        {
            StringBuilder builder = new StringBuilder();
            if (_order != SortOrder.None)
            {
                builder.Append("ORDER BY ");
                for (int x = 0; x < _columns.Count; x++)
                {
                    if (x > 0)
                        builder.Append(", ");

                    if (_columns[x].Parent != null &&
                        _columns[x].Parent is ITable)
                    {
                        (context as SqlQueryContext).EnsureAlias(_columns[x].Parent as ITable);                            
                        builder.Append("[" + (_columns[x].Parent as ITable).Alias + "].");
                    }

                    builder.Append("[" + _columns[x].Name + "]");
                }

                switch (_order)
                {
                    case SortOrder.Asc:
                        builder.Append(" ASC");
                        break;
                    case SortOrder.Desc:
                        builder.Append(" DESC");
                        break;
                }
            }
            return builder.ToString();
        }

        #endregion

        #region Object overrides
        public override string ToString()
        {
            return ToSql();
        }
        #endregion
    }
}
